//
//  XZStudentDetailVC.m
//  优学荟管理系统
//
//  Created by edz on 2018/1/10.
//  Copyright © 2018年 星道三好. All rights reserved.
//

#import "XZStudentDetailVC.h"
#import "XZStudentClassCell.h"
#import "XZHeadeView.h"
#import "XZStudentdetailModel.h"

@interface XZStudentDetailVC ()<UITableViewDelegate, UITableViewDataSource>

@property (strong, nonatomic) UITableView *tableView;

@property (nonatomic, assign) NSInteger page;
@property (nonatomic, assign) BOOL isTrue;
@property (nonatomic, strong) NSMutableArray <XZStudentdetailModel *>*dataSources;
@property (nonatomic, strong) XZHeadeView *headeView;
@end

@implementation XZStudentDetailVC

- (void)viewWillAppear:(BOOL)animated {
    
    [super viewWillAppear:animated];
    
    [self.navigationController.navigationBar setBackgroundImage:[LLTools createImageWithColor:ColorRGB(255, 255, 255)] forBarMetrics:(UIBarMetricsDefault)];
    [self.navigationController.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName:ColorRGB(51,51,51)}];
}

- (void)viewWillDisappear:(BOOL)animated {
    
    [super viewWillDisappear:animated];
    
    [self.navigationController.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName:ColorRGB(255,255,255)}];
    [self.navigationController.navigationBar setBackgroundImage:[LLTools createImageWithColor:ColorRGB(47, 204, 138)] forBarMetrics:(UIBarMetricsDefault)];

}

- (XZHeadeView *)headeView {
    if (!_headeView) {
        _headeView = [[XZHeadeView alloc] initwithStudentName:self.dataSources[0].petName];
    }
    return _headeView;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"学生详情";
    
    [self setupUI];
    [self setUpRefresh];
    _dataSources = [NSMutableArray array];
    self.navigationItem.leftBarButtonItem = [UIBarButtonItem itemWithTargat:self action:@selector(Pop) image:@"icon_back_student_sign" highImage:@""];
}

#pragma mark --- 上拉加载和下拉刷新方法的实现
- (void)setUpRefresh{
    
    //下拉刷新
    self.tableView.mj_header  = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(downRefresh)];
    //自动更改透明度
    self.tableView.mj_header.automaticallyChangeAlpha = YES;
    //进入刷新状态
    [self.tableView.mj_header beginRefreshing];
    
    //上拉加载
    self.tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(upRefresh)];
    //结束头部刷新
    [self.tableView.mj_header endRefreshing];
    //结束尾部刷新
    [self.tableView.mj_footer endRefreshing];
    
    
}

/**
 *  上拉加载
 */
- (void)upRefresh{
    
    self.isTrue = NO;
    self.page++;
    [self setNetWork];
    
}
/**
 *  下拉刷新
 */

- (void)downRefresh{
    self.isTrue = YES;
    self.page = 1;
    [self setNetWork];
    
    
}

- (void)setNetWork{
    //http://192.168.0.226:8080/StarShine/ys/trainLesson.do?action=selStudentById&uid=1&pageNumber=
    
    
    NSString *url = [NSString stringWithFormat:@"trainLesson.do?action=selStudentById&uid=%@&pageNumber=%ld",self.userID,(long)self.page];
    
    
    
    NSLog(@"%@ %@",LLBaseURL(url),[AccountTool shareAccountTool].currentAccount.authCode);
    
    
    [SVProgressHUD setDefaultStyle:(SVProgressHUDStyleCustom)];
    [SVProgressHUD  setBackgroundColor:ColorRGB(4, 4, 4)];
    [SVProgressHUD setForegroundColor:[UIColor whiteColor]];
    [SVProgressHUD showWithStatus:LLLoading];
    
    [NetManager Get:LLBaseURL(url) Auth:YES Params:nil Success:^(id Obj) {
        
        
        [SVProgressHUD dismiss];
        
        if ([[Obj valueForKey:@"code"]integerValue] == 1000) {
            if (self.isTrue == YES) {
                [self.dataSources removeAllObjects];
            }
            
            NSDictionary *dict = [Obj valueForKey:@"t"];
            
            NSArray *arr = [dict valueForKey:@"dataList"];
            
        
            
            if (arr != nil && ![arr isKindOfClass:[NSNull class]] && arr.count != 0){
                for (NSDictionary *dic in arr) {
                    XZStudentdetailModel *model = [XZStudentdetailModel new];
                    [model setValuesForKeysWithDictionary:dic];
                    [self.dataSources addObject:model];
                    self.headeView.url = model.avatar;
                }
                
                _tableView.tableHeaderView = self.headeView;
                [self.tableView reloadData];
            }
        } else {
            [MBProgressHUD showError:Obj[@"msg"]];
        }
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
    } Fail:^(NSError *Error) {
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
        [SVProgressHUD dismiss];
    }];
    
}

#pragma mark - 删除学生
- (void)deleteStudent:(UIButton *)sender {
    NSString *url = [NSString stringWithFormat:@"trainLesson.do?action=delStudentNotValid&uid=%@&enrollInfoId=0&type=0",self.userID];
    
    NSLog(@"%@ %@",LLBaseURL(url),[AccountTool shareAccountTool].currentAccount.authCode);
    
    
    [SVProgressHUD setDefaultStyle:(SVProgressHUDStyleCustom)];
    [SVProgressHUD  setBackgroundColor:ColorRGB(4, 4, 4)];
    [SVProgressHUD setForegroundColor:[UIColor whiteColor]];
    [SVProgressHUD showWithStatus:LLLoading];
    
    [NetManager Post:LLBaseURL(url) Auth:YES Params:nil Success:^(id Obj) {
        if ([[Obj valueForKey:@"code"]integerValue] == 1000) {
           [SVProgressHUD setStatus:Obj[@"msg"]];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                if (_callBack) {
                    _callBack();
                }
                [SVProgressHUD dismiss];
                [self.navigationController popViewControllerAnimated:YES];
            });
        }
    } Fail:^(NSError *Error) {
      
        [SVProgressHUD dismiss];
    }];
}

- (void)Pop {
    
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)setupUI {
    
    UIButton *delegate = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 30, 30)];
    [delegate setBackgroundImage:[UIImage imageNamed:@"icon_xaingqin_deleted_default"] forState:UIControlStateNormal];
    [delegate addTarget:self action:@selector(deleteStudent:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *rightBarItem = [[UIBarButtonItem alloc] initWithCustomView:delegate];
    self.navigationItem.rightBarButtonItem = rightBarItem;
    
    _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:(UITableViewStylePlain)];
    _tableView.delegate = self;
    _tableView.dataSource = self;

    _tableView.tableFooterView = [UIView new];
    _tableView.backgroundColor = RGBColor(245, 245, 245);
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _tableView.rowHeight = 172;
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.tableView.contentInset = UIEdgeInsetsMake(-54, 0, 0, 0);
    [_tableView registerNib:[UINib nibWithNibName:@"XZStudentClassCell" bundle:nil] forCellReuseIdentifier:@"StudentClass"];
    [self.view addSubview:_tableView];
    
    [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view);
    }];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _dataSources.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    XZStudentClassCell *cell = [tableView dequeueReusableCellWithIdentifier:@"StudentClass" forIndexPath:indexPath];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.model = self.dataSources[indexPath.row].model;

    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
}

@end
